﻿using System;
using System.Runtime.Caching;
using Hiver.Util;
using Hiver.Util.Config;
using Hiver.Util.Config.Model;
using Hiver.Cache.Interfaces;

namespace Hiver.Cache
{
    /// <summary>
    /// 文件缓存
    /// </summary>
    public class FilesCache : ICache
    {
        /// <summary>
        /// 文件缓存对象
        /// </summary>
        public FileCache cache = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FilesCache()
        {
            ApplicationConfigModel config = YamlHelper<ApplicationConfigModel>.Load();
            if (config == null)
                Error.Show(1);
            string path = AppDomain.CurrentDomain.BaseDirectory;
            if (config.CachePath == null)
                path += "/Cache/";
            else
                path += config.CachePath;
            cache = new FileCache(path);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public object Set(string name, object value)
        {
            cache[name] = value;
            return value;
        }

        /// <summary>
        /// 读取缓存
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object Get(string name)
        {
            return cache[name];
        }

        /// <summary>
        /// 判断是否有缓存项
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Has(string name)
        {
            return cache.Contains(name);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object Remove(string name)
        {
            return cache.Remove(name);
        }

        /// <summary>
        /// 清空缓存
        /// </summary>
        /// <returns></returns>
        public long Clear()
        {
            return cache.CleanCache();
        }

        /// <summary>
        /// 刷新缓存
        /// </summary>
        public void Flush()
        {
            cache.Flush();
        }
    }
}